# -*- coding:utf-8 -*-
import tornado.web
import time
from toTest.commons import mod_Sessions
import io
import check_Code

class LoginHandler(tornado.web.RequestHandler):
	def get(self, *args, **kwargs):
		self.render("account/login.html",status_text='')
	def post(self, *args, **kwargs):
		username = self.get_argument('username',None)
		password = self.get_argument('password',None)
		check = self.get_argument('auto',None)  # auto为`7天免登录的name值`
		print check
		if username == 'admin' and password == '123':
			if check:
				# self.set_cookie为原生的,self.set_secure_cookie()为加密的
				# 使用加密的,还需要在settings中配置：'cookie_secret':'自定义的字符串'
				self.set_cookie('auth','1',expires_days=7)
				self.set_cookie('username',username,expires_days=7)  # 只用cookie，不用session时简单验证
			else:
				tt = time.time() + 30  # time.time()为时间戳
				self.set_cookie('auth', '1',expires=tt)
				self.set_cookie('username', username,expires=tt)
			self.redirect('/account/manager')
		self.render("account/login.html",status_text='登录失败')

class managerHandler(tornado.web.RequestHandler):
	def get(self, *args, **kwargs):
		co = self.get_cookie('auth')
		if co == '1':
			self.render("account/manager.html")
		else:
			self.redirect('/account/login')

class LogoutHandler(tornado.web.RequestHandler):
	def get(self, *args, **kwargs):
		self.set_cookie('auth','0')
		self.redirect('/account/login')

class Login_ajaxHandler(tornado.web.RequestHandler):
	def get(self, *args, **kwargs):
		self.render("account/login_ajax.html")

	def post(self, *args, **kwargs):
		dic = {'status': True,'message': ''}
		username = self.get_argument('username')
		password = self.get_argument('password')
		print username,password
		if username == 'admin' and password == 'aaaaaa':
			self.redirect('/account/manager')
		else:
			dic['status'] = False
			dic['message'] = '用户名或密码错误'
		import json
		self.write(json.dumps(dic))

class BaseHandler(tornado.web.RequestHandler):
	def initialize(self):
		self.session = mod_Sessions.MemcachedSession(self)

class Login_codeHandler(BaseHandler):
	def get(self, *args, **kwargs):
		self.render('account/login_code.html', status='')

	def post(self, *args, **kwargs):
		user = self.get_argument('user',None)
		password = self.get_argument('password', None)
		code = self.get_argument('code', None)
		check_code = self.session['CheckCode']
		if code.upper() == check_code.upper():  # upper()将字母全变大写
			self.write('验证码正确')
		else:
			self.render('account/login_code.html', status='验证码错误')


class Login_checkcodeHandler(BaseHandler):
	def get(self, *args, **kwargs):
		mstream = io.BytesIO()  # 相当于内存文件（在内存里临时创建文件）
		img, code = check_Code.create_validate_code()  # 创建图片，并在图片上写入验证码
		img.save(mstream, 'GIF')  # 将图片对象写入到mstream
		self.write(mstream.getvalue())
		self.session['CheckCode'] = code  # 保存每个用户的验证码


